package serverlet;

import Server.ManagerServer;
import user.Manager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "InitLoginServlet", urlPatterns = "/login")
public class InitLoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String account = null;
        String password = null;

        Cookie[] cookies = request.getCookies();
        if(null==cookies){
            System.out.println("没有cookies");
        }else {
            for(Cookie tc : cookies){
                if("account".equals(tc.getName())){
                    account=tc.getValue();
                }else if("password".equals(tc.getName())){
                    password=tc.getValue();
                }
            }
        }

        if(null==account&&null==password){
            System.out.println("第一次需要登录！");
            Cookie cookie = new Cookie("account", "default");
            response.addCookie(cookie);
            Cookie cookie1 = new Cookie("password", "default");
            response.addCookie(cookie1);
            System.out.println("创建Cookie成功！");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }

        //创建ManagerServerice
        ManagerServer managerServer = new ManagerServer();
        Manager manager = managerServer.managerLoginServer(new Manager(account, password));
        if(null == manager){
            System.out.println("登陆失败，账号或密码失败");
            request.setAttribute("error","登陆失败，用户名或密码错误");
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else {
            System.out.println("登陆成功，欢迎使用");
            request.getSession().setAttribute("account",manager.getAccount());
            request.getSession().setAttribute("password",manager.getPassword());
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/managerinit");
            requestDispatcher.forward(request,response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
